package com.ccys.cms.service.formulation.impl;

import com.ccys.cms.service.formulation.FormulationService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.web.formulation.FormulationDto;
import com.ccys.db.entity.TblFormulation;
import com.ccys.db.mapper.TblFormulationMapper;
import com.ccys.db.mapper.TblFormulationQuantityTypeMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.vo.web.formulation.FormulationVo;
import com.ccys.db.vo.web.formulation.UomCountVo;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;


@Service
public class FormulationServiceImpl extends BaseServiceImpl<TblFormulation> implements FormulationService {


    @Resource
    private TblFormulationMapper formulationMapper;

    @Resource
    private TblFormulationQuantityTypeMapper quantityTypeMapper;

    @Override
    public ResponseResult getPage(FormulationDto dto) {
        PageDto.startPage();
        //根据当前用户groupid
        //超级管理员的区分 (超级管理员没有groupId 不会进查询条件)
        if (StringUtils.isEmpty(dto.getGroupId())) {
            String groupId = dto.getGroupId();
            dto.setGroupId(groupId);
        }
        List<FormulationVo> list = formulationMapper.getList(dto);
        PageInfo<FormulationVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult change(TblFormulation model) {

        //修改allow_multiple为否的时候，判断是否有负数个quantitytype，如果有就不允许修改，抛出异常
        if (Objects.nonNull(model.getAllowMultiple())&&1 == model.getAllowMultiple()) {
            List<UomCountVo> countVoList = quantityTypeMapper.getUomCountByFormulationId(model.getId());
            for (UomCountVo vo : countVoList) {
                Integer uomCount = vo.getUomCount();
                if (uomCount > 1) {
                    return ResponseResult.error(" This formulation has multiple UOM ");
                }
            }
        }
        int i = this.insertOrUpdate(model);

        return ResponseResult.update(i);
    }
}
